﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml.Linq;
using OAuth.Providers.ETrade.Model;
using ReactiveOAuth;

#if WINDOWS_PHONE
using Microsoft.Phone.Reactive;
#else
using System.Reactive.Linq;
#endif

namespace OAuth.Providers.ETrade
{
    
    public class Market
    {

        public AccessToken AccessToken { private get; set; }

        public Market(AccessToken accessToken)
        {
            AccessToken = accessToken;
        }

        public event ObjectEventHandler<ObservableCollection<Quote>> GetQuotesCompleted;

        public void GetQuotes(string symbol, params string[] otherSymbols)
        {
            string quoteUrl = otherSymbols.Aggregate(symbol, (current, s) => string.Concat(current, ",", s));

            var quotes = new ObservableCollection<Quote>();

            var client = new OAuthClient(Settings.ConsumerKey, Settings.ConsumerSecret, AccessToken);
            client.Url = String.Concat(Settings.MarketQuoteUrl, "/", quoteUrl);
            client.MethodType = MethodType.Get;
            client.GetResponseText()
                .Select(XElement.Parse)
                .SelectMany(x => x.Descendants("QuoteData"))
                .Select(x => new Quote
                                 {
                                     Symbol = x.Element("product").Element("symbol").Value,
                                     AdjNonAdjFlag = bool.Parse(x.Element("all").Element("adjNonAdjFlag").Value),
                                     AnnualDividend = double.Parse(x.Element("all").Element("annualDividend").Value),
                                     Ask = double.Parse(x.Element("all").Element("ask").Value),
                                     AskExchange = x.Element("all").Element("askExchange").Value,
                                     AskSize = int.Parse(x.Element("all").Element("askSize").Value),
                                     AskTime = x.Element("all").Element("askTime").Value.ToDateTime(),
                                     Bid = double.Parse(x.Element("all").Element("bid").Value),
                                     BidExchange = x.Element("all").Element("bidExchange").Value,
                                     BidSize = int.Parse(x.Element("all").Element("bidSize").Value),
                                     BidTime = x.Element("all").Element("bidTime").Value.ToDateTime(),
                                     ChangeClose = double.Parse(x.Element("all").Element("chgClose").Value),
                                     ChangeClosePercent = double.Parse(x.Element("all").Element("chgClosePrcn").Value),
                                     CompanyName = x.Element("all").Element("companyName").Value,
                                     DayToExpiration = int.Parse(x.Element("all").Element("daysToExpiration").Value),
                                     DirLast = x.Element("all").Element("dirLast").Value,
                                     Dividend = double.Parse(x.Element("all").Element("dividend").Value),
                                     Eps = double.Parse(x.Element("all").Element("eps").Value),
                                     EstEarnings = double.Parse(x.Element("all").Element("estEarnings").Value),
                                     ExDivDate = x.Element("all").Element("exDivDate").Value,
                                     ExchgLastTrade = x.Element("all").Element("exchgLastTrade").Value,
                                     Fsi = x.Element("all").Element("fsi").Value,
                                     High = double.Parse(x.Element("all").Element("high").Value),
                                     High52 = double.Parse(x.Element("all").Element("high52").Value),
                                     HighAsk = double.Parse(x.Element("all").Element("highAsk").Value),
                                     HighBid = double.Parse(x.Element("all").Element("highBid").Value),
                                     LastTrade = double.Parse(x.Element("all").Element("lastTrade").Value),
                                     Low = double.Parse(x.Element("all").Element("low").Value),
                                     Low52 = double.Parse(x.Element("all").Element("low52").Value),
                                     LowAsk = double.Parse(x.Element("all").Element("lowAsk").Value),
                                     LowBid = double.Parse(x.Element("all").Element("lowBid").Value),
                                     NumTrades = int.Parse(x.Element("all").Element("numTrades").Value),
                                     Open = double.Parse(x.Element("all").Element("open").Value),
                                     OpenInterest = double.Parse(x.Element("all").Element("openInterest").Value),
                                     OptionStyle = x.Element("all").Element("optionStyle").Value,
                                     OptionUnderlier = x.Element("all").Element("optionUnderlier").Value,
                                     PreviousClose = double.Parse(x.Element("all").Element("prevClose").Value),
                                     PreviousDayVolume = int.Parse(x.Element("all").Element("prevDayVolume").Value),
                                     PrimaryExchange = x.Element("all").Element("primaryExchange").Value,
                                     SymbolDescription = x.Element("all").Element("symbolDesc").Value,
                                     TodayClose = double.Parse(x.Element("all").Element("todayClose").Value),
                                     TotalVolume = int.Parse(x.Element("all").Element("totalVolume").Value),
                                     Upc = int.Parse(x.Element("all").Element("upc").Value),
                                     Volume10Day = int.Parse(x.Element("all").Element("volume10Day").Value),

                                     LastQuote = x.Element("dateTime").Value.ToDateTime(),
                                 })
                .ObserveOnDispatcher()
                .Subscribe(quotes.Add,
                          (ex) => { },
                           () =>
                               {
                                   if (GetQuotesCompleted != null)
                                       GetQuotesCompleted(quotes);
                               });
        }

    }

}